<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n'
import { useIcon } from '@/hooks/web/useIcon'
import { reactive, watch, ref } from 'vue'
import {
  goodsSelect,
  transportSelect,
  placestartSelect,
  clientSelect,
  storeSelect,
  consigneeSelect,
  placeendSelect,
  submarketSelect
} from '@/api/common'
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElRow,
  ElCol,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElButton,
  ElDivider,
  ElUpload,
  ElTable,
  ElTableColumn
} from 'element-plus'

import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
const { t } = useI18n()

import * as xlsx from 'xlsx'
import { useCache } from '@/hooks/web/useCache'

const addIcon = useIcon({ icon: 'gala:add' })
const delIcon = useIcon({ icon: 'material-symbols:delete-outline' })

const { wsCache } = useCache()
const getToken = wsCache.get('userInfo') ? wsCache.get('userInfo').token : ''
const fileList = ref<UploadUserFile[]>([])

/**
 * 把文件按照二进制进行读取
 * @param file
 * @returns
 */
const readFile = (file: File) => {
  return new Promise((resolve) => {
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = (ev) => {
      resolve(ev.target?.result)
    }
    console.log(reader)
  })
}

/**
 * 根据sheet索引读取Excel文件中的数据
 /**@param file 文件
 /** @param sheetIndex excel文件中sheet表索引 默认是从0开始
 /**@returns  将表中的数据以json形式的数据返回
*/
const readExcelFile = async (file: File, sheetIndex: number) => {
  let data: any = await readFile(file)
  let workbook = xlsx.read(data, { type: 'binary' })
  let worksheet = workbook.Sheets[workbook.SheetNames[sheetIndex]]
  data = xlsx.utils.sheet_to_json(worksheet)
  console.log(data)
  let key = {
    件数: 'piece',
    货值: 'worth',
    名称: 'gname',
    备注: 'remark',
    宽: 'width',
    房间号: 'room',
    装箱数: 'quantity',
    重量: 'weight',
    长: 'length',
    颜色: 'colour',
    高: 'high'
  }
  if (data && data.length > 0) {
    form.warehousingItems = data.length
    data.forEach((dataItem: any, index) => {
      let obj: any = {}
      for (let name in dataItem) {
        obj[key[name]] = dataItem[name]
      }
      // console.log('---obj---', obj)

      let pieceItem = reactive({
        key: index + 1,
        title: `${t('warehousingEntryAddWrite.goodsEntry')} ${index + 1} ：`,
        goods_id: '', // 货物种类
        worth: '', // 单件货值
        // list: [
        // {
        total: Number(obj.piece ? obj.piece : 1) * Number(obj.quantity),
        ...obj
        // }
        // ]
      })
      console.log('---pieceItem---', pieceItem)
      form.pieceArray.push(pieceItem)
    })
  }
  // return data
}
const before = (file: any) => {
  readExcelFile(file, 0)
  return false
}
const props = defineProps({
  currentRow: {
    type: Object as any,
    default: () => null
  }
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    form.id = currentRow.id
    // form.typeOfGoods = currentRow.goods_id
    if (currentRow.goodsType && currentRow.goodsType.length > 0) {
      currentRow.goodsType.forEach((item) => {
        // form.typeOfGoods.push(item.id)
        form.typeOfGoods = item.id
      })
    }
    form.store_id = Number(currentRow.store_id)
    form.modeOfTransport = currentRow.transport
    form.origin = currentRow.placestart
    form.relatedCustomers = currentRow.client_code
    console.log(currentRow.entrytime)
    form.warehousingTime = currentRow.entertime
    form.warehousingTime = currentRow.entertime //出库时间
    form.productNameRemarks = currentRow.remark
    form.warehousingItems = currentRow.piece
    form.recipient = currentRow.shouhuo
    // form.destination = Number(currentRow.placeend)
    // form.warehousingTime = currentRow.entertime
    form.destination = currentRow.placeend
    form.submarket = currentRow.submarket
    form.out_date = currentRow.out_date
    let goodsStr = currentRow.goods.replace(/&quot;/g, '"')
    let goodsArr: any = JSON.parse(goodsStr)
    goodsArr.forEach((item, i) => {
      let pieceItem = {
        key: i + 1,
        title: `${t('warehousingEntryAddWrite.goodsEntry')} ${i + 1} ：`,
        gname: item.gname, // 名称
        goods_id: Number(item.goods_id), // 货物种类
        worth: item.worth, // 单件货值
        piece: item.piece,
        quantity: item.quantity,
        room: item.room,
        colour: item.colour,
        length: item.length,
        width: item.width,
        high: item.high,
        weight: item.weight,
        remark: item.remark,
        total: item.total,
        price: item.price
      }
      form.pieceArray.push(pieceItem)
    })
  }
)
//form类型
interface form {
  id: string
  typeOfGoods: any
  store_id: any
  modeOfTransport: any
  origin: any
  relatedCustomers: any
  warehousingTime: any
  out_date: any
  productNameRemarks: any
  warehousingItems: any
  recipient: any
  destination: any
  pieceArray: any
  fahuo: any
  submarket: any
}
const form = reactive<form>({
  id: '',
  typeOfGoods: '', //货品种类
  store_id: '', //货物位置
  modeOfTransport: '', //运输方式
  origin: '', //始发地
  relatedCustomers: '', //关联客户
  warehousingTime: '', //入库时间
  out_date: '', //出库时间
  productNameRemarks: '', //品名备注
  warehousingItems: '', //入库件数，
  recipient: '', // 收件人
  destination: '', // 目的地
  fahuo: '', // 发货人
  submarket: '', //分货市场
  pieceArray: []
})
//表单验证
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<form>>({
  typeOfGoods: [{ required: true, message: '货品种类必填', trigger: 'blur' }],
  store_id: [{ required: true, message: '货品位置必填', trigger: 'blur' }],
  relatedCustomers: [{ required: true, message: '客户号必填', trigger: 'blur' }],
  recipient: [{ required: true, message: '收货人必填', trigger: 'blur' }]
})
// 物品的种类选项
const typeOfGoodsArr: any = reactive([])
const getGoodsSelect = async () => {
  // let goodsTypeArr: any = []
  let res: any = await goodsSelect({})
  res.data.list.forEach((item) => {
    typeOfGoodsArr.push({
      label: item.name,
      value: item.id
    })
  })
}
getGoodsSelect()

//货物位置
const locationOfGoodsArr: any = reactive([])
const getStoreSelect = async () => {
  let res: any = await storeSelect({})
  res.data.list.forEach((item) => {
    item.type == 1 &&
      locationOfGoodsArr.push({
        label: item.name,
        value: item.id
      })
  })
}
getStoreSelect()
// 运输方式
const modeOfTransportArr: any = reactive([])
const getTransportSelect = async () => {
  let res: any = await transportSelect({})
  res.data.list.forEach((item) => {
    modeOfTransportArr.push({
      label: item.name,
      value: item.name
    })
  })
}
getTransportSelect()

//始发地
const originArr: any = reactive([])
const getOriginSelect = async () => {
  let res: any = await placestartSelect({})
  res.data.list.forEach((item) => {
    originArr.push({
      label: item.name,
      value: item.name
    })
  })
}
getOriginSelect()

//关联客户
const relatedCustomersArr: any = reactive([])
const getClientSelect = async () => {
  let res: any = await clientSelect({})
  res.data.list.forEach((item) => {
    relatedCustomersArr.push({
      label: item.code,
      value: item.code
    })
  })
}
getClientSelect()

//关联客户号
const khChange = (value) => {
  console.log('---khChange', value)
  form.fahuo = value
}

//收件人
const consigneeArr: any = reactive([])
const getConsigneeSelect = async () => {
  let res: any = await consigneeSelect({})
  console.log('---收件人下拉选择---', res)
  res.data.list.forEach((item) => {
    consigneeArr.push({
      label: item.name,
      value: item.name,
      code: item.client_code,
      placeend: item.placeend,
      submarket: item.submarket
    })
  })
}
const selectKehu = (e) => {
  let data = consigneeArr.find((item) => {
    console.log('---?---', item)
    return item.value == e
  })
  form.relatedCustomers = data.code
  form.destination = data.placeend?.name
  form.submarket = data.submarket?.name
}
getConsigneeSelect()

//目的地
const placeendArr: any = reactive([])
const getPlaceendSelect = async () => {
  let res: any = await placeendSelect({})
  console.log('---目的地下拉选择---', res)
  res.data.list.forEach((item) => {
    placeendArr.push({
      label: item.name,
      value: item.name
    })
  })
}
getPlaceendSelect()

//分货市场
const submarketArr: any = reactive([])
const getsubmarketSelect = async () => {
  let res: any = await submarketSelect()
  res.data.list.forEach((item) => {
    submarketArr.push({
      label: item.name,
      value: item.name
    })
  })
}
getsubmarketSelect()

const addPieceItem = () => {
  let pieceItem = reactive({
    key: form.pieceArray.length + 1,
    title: `${t('warehousingEntryAddWrite.goodsEntry')} ${form.pieceArray.length + 1} ：`,
    gname: '', // 名称
    goods_id: '', // 货物种类
    worth: '', // 单件货值
    // list: [
    // {
    piece: '',
    quantity: '',
    room: '',
    colour: '',
    length: '',
    width: '',
    high: '',
    weight: '',
    remark: '',
    price: ''
    // }
    // ]
  })
  form.pieceArray.push(pieceItem)
  form.warehousingItems = form.pieceArray.length
}
const delGoods = (i) => {
  form.pieceArray.splice(i, 1)
  form.warehousingItems = form.pieceArray.length
}
const rkNumInput = () => {
  let oldLength = form.pieceArray.length
  if (form.warehousingItems) {
    let forNum = 0
    if (oldLength > form.warehousingItems) {
      form.pieceArray = []
      forNum = form.warehousingItems
    } else {
      forNum = form.warehousingItems - oldLength
    }

    for (let i = 1; i <= forNum; i++) {
      let pieceItem = reactive({
        key: i,
        title: `${t('warehousingEntryAddWrite.goodsEntry')} ${i} ：`,
        gname: '', // 名称
        // goods_id: '', // 货物种类
        goods_id: form.typeOfGoods || '',
        worth: '', // 单件货值
        list: [
          {
            piece: '',
            quantity: '',
            room: '',
            colour: '',
            length: '',
            width: '',
            high: '',
            weight: '',
            remark: '',
            price: ''
          }
        ]
      })
      form.pieceArray.push(pieceItem)
    }
  } else {
    form.pieceArray = []
  }

  console.log('---form.pieceArray---', form.pieceArray)
}

const sumTotal = () => {
  // let total = 0 //总合计
  for (let a = 0; a < form.pieceArray.length; a++) {
    form.pieceArray[a].total =
      (form.pieceArray[a].piece ? form.pieceArray[a].piece : 1) *
      (form.pieceArray[a].quantity ? form.pieceArray[a].quantity : 0)
  }
}

// 回车计算总和
const keyEnterGetSum = (row) => {
  let price = String(row.piece)
  let a = price.split('+')
  if (a.length > 1) {
    let c = 0
    for (let b = 0; b < a.length; b++) {
      c += Number(a[b])
    }
    form.pieceArray[row.key - 1].piece = c
  } else {
    form.pieceArray[row.key - 1].piece = a[0]
  }
}

watch(form, (newVal, oldVal) => {
  // if (form.typeOfGoods) {
  //   form.pieceArray.length > 0 &&
  //     form.pieceArray.forEach((item) => {
  //       item.goods_id = form.typeOfGoods
  //     })
  // }
})

defineExpose({
  getFormData: () => {
    return form
  },
  getRlus: () => {
    return ruleFormRef
  }
})
//打包计算
// 按件  件数合计 手动输入*单价
</script>

<template>
  <ElForm :model="form" ref="ruleFormRef" label-width="auto" :rules="rules">
    <ElRow>
      <ElCol :span="8">
        <ElFormItem
          label-width="100px"
          :label="t('warehousingEntry.typeOfGoods')"
          prop="typeOfGoods"
        >
          <ElSelect
            clearable
            v-model="form.typeOfGoods"
            :placeholder="t('alertEn.PleaseSelectThetypeOfGoods')"
            filterable
          >
            <ElOption
              v-for="item in typeOfGoodsArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="8">
        <ElFormItem label-width="100px" :label="t('warehousingEntry.locationOfGoods')">
          <ElSelect
            clearable
            v-model="form.store_id"
            :placeholder="t('alertEn.PleaseSelectThelocationOfGoods')"
            filterable
          >
            <ElOption
              v-for="item in locationOfGoodsArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="8">
        <ElFormItem label-width="100px" :label="t('warehousingEntryAddWrite.warehousingTime')">
          <ElDatePicker
            v-model="form.warehousingTime"
            type="date"
            :placeholder="t('alertEn.PleaseSelectTheStorageTime')"
            :shortcuts="[
              {
                text: '今天',
                value: new Date()
              }
            ]"
          />
        </ElFormItem>
      </ElCol>
      <!-- <ElCol :span="8">
        <ElFormItem label-width="100px" :label="t('warehousingEntryAddWrite.modeOfTransport')">
          <ElSelect
            clearable
            v-model="form.modeOfTransport"
            :placeholder="t('alertEn.PleaseSelectThemodeOfTransport')"
            filterable
          >
            <ElOption
              v-for="(item, index) in modeOfTransportArr"
              :key="item.value"
              :label="`${index + 1}.${item.label}`"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol> -->
    </ElRow>
    <ElRow>
      <ElCol :span="8">
        <ElFormItem label-width="100px" :label="t('router.origin')">
          <ElSelect
            v-model="form.origin"
            :placeholder="t('alertEn.PleaseSelectTheorigin')"
            filterable
            clearable
          >
            <ElOption
              v-for="item in originArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="8">
        <ElFormItem label-width="100px" :label="t('warehousingEntry.destination')">
          <ElSelect
            v-model="form.destination"
            :placeholder="t('common.selectText')"
            clearable
            filterable
          >
            <ElOption
              v-for="item in placeendArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="8">
        <ElFormItem label-width="100px" :label="t('router.distributionMarket')">
          <ElSelect
            v-model="form.submarket"
            :placeholder="t('common.selectText')"
            clearable
            filterable
          >
            <ElOption
              v-for="item in submarketArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="8">
        <ElFormItem label-width="100px" label="客户号" prop="relatedCustomers">
          <ElSelect
            v-model="form.relatedCustomers"
            :placeholder="t('alertEn.PleaseSelectTherelatedCustomers')"
            filterable
            clearable
            @change="khChange"
          >
            <ElOption
              v-for="item in relatedCustomersArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="8">
        <ElFormItem label-width="100px" :label="t('invoice.deliveryTime')">
          <ElDatePicker
            v-model="form.out_date"
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="t('common.selectText')"
            :shortcuts="[
              {
                text: '今天',
                value: new Date()
              }
            ]"
          />
        </ElFormItem>
      </ElCol>
    </ElRow>
    <ElRow>
      <ElCol :span="8">
        <ElFormItem
          label-width="100px"
          prop="recipient"
          :label="t('purchaseOrderAddWrite.recipient')"
        >
          <ElSelect
            v-model="form.recipient"
            :placeholder="t('common.selectText')"
            @change="selectKehu"
            filterable
            clearable
          >
            <ElOption
              v-for="item in consigneeArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="3">
        <ElFormItem label-width="100px" label="入库条目">
          <ElInput v-model="form.warehousingItems" />
        </ElFormItem>
      </ElCol>
      <ElCol :offset="1" :span="2">
        <ElButton type="primary" circle :icon="addIcon" size="small" @click="rkNumInput" />
      </ElCol>
      <ElCol :span="6">
        <ElFormItem
          label-width="100px"
          prop="productNameRemarks"
          :label="t('personnelManagementemp.notes')"
        >
          <ElInput v-model="form.productNameRemarks" />
        </ElFormItem>
      </ElCol>

      <!-- <ElCol :offset="1" :span="2" @click="subSm">
        <ElUpload
          class="upload_file"
          v-model:file-list="fileList"
          :limit="1"
          accept="xlsx, xls"
          :headers="{
            token: getToken
          }"
          :before-upload="before"
        >
          <ElButton type="primary">导入</ElButton>
        </ElUpload>
      </ElCol> -->
    </ElRow>

    <ElRow>
      <ElCol :span="24">
        <ElTable :data="form.pieceArray" style="width: 100%" ref="multipleTable">
          <ElTableColumn prop="goods_id" :label="t('warehousingEntry.typeOfGoods')">
            <template #default="scope">
              <!-- <ElInput v-model="scope.row.goods_id" :placeholder="t('common.inputText')" /> -->
              <ElSelect
                label-in-value
                v-model="scope.row.goods_id"
                :placeholder="t('alertEn.PleaseSelectThetypeOfGoods')"
              >
                <ElOption
                  v-for="item in typeOfGoodsArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElSelect>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="gname" label="款式类型">
            <template #default="scope">
              <ElInput v-model="scope.row.gname" :placeholder="t('common.inputText')" />
              <ElButton type="danger" :icon="delIcon" circle @click="delGoods(scope.$index)" />
            </template>
          </ElTableColumn>

          <ElTableColumn prop="gname" label="品名">
            <template #default="scope">
              <ElInput v-model="scope.row.gname" :placeholder="t('common.inputText')" />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="piece" :label="t('warehousingEntryAddWrite.numberOfPieces')">
            <template #default="scope">
              <ElInput
                v-model="scope.row.piece"
                :placeholder="t('common.inputText')"
                @keyup.enter="keyEnterGetSum(scope.row)"
              />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="worth" :label="t('warehousingEntryAddWrite.value')">
            <template #default="scope">
              <ElInput v-model="scope.row.worth" :placeholder="t('common.inputText')" />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="remark" :label="t('purchaseOrderAddWrite.notes')">
            <template #default="scope">
              <ElInput v-model="scope.row.remark" :placeholder="t('common.inputText')" />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="remark" label="操作">
            <template #default="scope">
              <ElButton type="danger" :icon="delIcon" circle @click="delGoods(scope.$index)" />
            </template>
          </ElTableColumn>
        </ElTable>
      </ElCol>
    </ElRow>
  </ElForm>
</template>
<style scoped lang="less">
.listForItem {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .el-col:nth-of-type(2) {
    font-size: var(--el-form-label-font-size);
    padding: 0 15px;
  }
  .el-col:nth-of-type(1) {
    padding-right: 15px;
  }
  .el-col:nth-of-type(6) {
    padding-left: 15px;
  }
  .el-divider--horizontal {
    margin: 0;
  }
  .el-form-item--default {
    margin-bottom: 0;
  }
}
</style>
